﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System;
using System.ComponentModel;
using System.Threading;
using Xceed.Silverlight.DataGrid.Utils;

namespace Xceed.Silverlight.DataGrid
{
  internal sealed class InhibitorFlag : INotifyPropertyChanged
  {
    #region Constructor

    internal InhibitorFlag()
    {
      m_propertyChangedHelper = new NotifyPropertyChangedHelper( this, this.RaisePropertyChangedEvent );
    }

    #endregion

    #region IsSet Property

    internal bool IsSet
    {
      get
      {
        return ( m_counter > 0 );
      }
    }

    private void RaiseIsSetChanged()
    {
      m_propertyChangedHelper.RaisePropertyChanged( () => this.IsSet );
    }

    private int m_counter; //0

    #endregion

    internal IDisposable Set()
    {
      return new InhibitorFlagCounter( this );
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChangedEvent( string propertyName )
    {
      if( this.PropertyChanged != null )
      {
        this.PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
      }
    }

    private readonly NotifyPropertyChangedHelper m_propertyChangedHelper;

    #endregion

    #region InhibitorFlagCounter Nested Type

    private sealed class InhibitorFlagCounter : IDisposable
    {
      internal InhibitorFlagCounter( InhibitorFlag owner )
      {
        m_owner = owner;

        Interlocked.Increment( ref owner.m_counter );
        m_owner.RaiseIsSetChanged();
      }

      public void Dispose()
      {
        this.Dispose( true );
        GC.SuppressFinalize( this );
      }

      private void Dispose( bool disposing )
      {
        if( m_disposed )
          return;

        m_disposed = true;

        Interlocked.Decrement( ref m_owner.m_counter );
        m_owner.RaiseIsSetChanged();
      }

      ~InhibitorFlagCounter()
      {
        this.Dispose( false );
      }

      private readonly InhibitorFlag m_owner;
      private bool m_disposed;
    }

    #endregion
  }
}
